﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using MinistryStandardPlatformWeb.Models;
using MinistryStandardPlatformEntity;
using MinistryStandardPlatformWeb.Controllers.RealTime;

namespace MinistryStandardPlatformWeb.Controllers.Reports
{
    [MenuAuthorized("45")]
    public class UnitWarningStatisticsController : Controller
    {
        //
        // GET: /UnitWarningStatistics/

        private MSPGpsDataContext context = new MSPGpsDataContext();
        private MSPDataContext context1 = new MSPDataContext();


        public ActionResult Index(string startTime, string endTime)
        {
            ViewBag.StartTime = startTime;
            ViewBag.EndTime = endTime;
            return View();
        }

        public ActionResult Data(string startTime, string endTime, string vehicles, int pageIndex = 1)
        {
            if (Session["SearchData"] != null)
            {
                return PartialView((Session["SearchData"] as IEnumerable<UnitWarningStatistics>).ToPagedList(pageIndex, CommonDictionary.PageSize));
            }

            //得到要查询的车辆id的list
            List<string> vehiclesList = vehicles.Split(';').ToList();
            
            //通过车辆得到要查询的单位
            var units=from v in context1.InfoVehicle
                      from u in context1.InfoUnit
                      where vehiclesList.Contains(v.SIM) &&
                      v.ParentUnitId==u.UNITID
                      orderby u.UNITNAME
                      select new UnitWarningStatistics()
                      {
                          UnitId=u.UNITID,
                          UnitName=u.UNITNAME,
                          ParentUnitName=u.InfoUnit1.UNITNAME
                      };
            List<UnitWarningStatistics> unitWarnings=units.Distinct().ToList();

            //获取这些单位的id
            List<string> unitsId=new List<string>();
            foreach(UnitWarningStatistics item in unitWarnings)
            {
                unitsId.Add(item.UnitId);
            }

            //获取这些单位下该用户有权限的车辆的sim卡号和所属单位
            var vehi = from r in context1.RightsDetails
                       from v in context1.InfoVehicle
                       where r.HasRight == true &&
                       r.UserId == CommonFunctions.GetLoginUser().UserId &&
                       unitsId.Contains(r.ParentNodeId) &&
                       v.Vehiclenum == r.NodeId
                       select new WarningInfo()
                       {
                           Sim = v.SIM,
                           ParentUnitId = v.ParentUnitId
                       };
            List<WarningInfo> vehicleList = vehi.ToList();

            //获取车辆的sim卡号
            List<string> vehicleSim = new List<string>();
            foreach (WarningInfo item in vehicleList)
            {
                vehicleSim.Add(item.Sim);
            }
            //查找所有报警
            var warnings = from w in context.GpsWarn
                           where vehicleSim.Contains(w.simId) &&
                           string.Compare(w.warnstarttime, startTime) >= 0 &&
                           string.Compare(w.warnstarttime, endTime) <= 0 
                           select new WarningInfo()
                               {
                                   VehicleId = w.vehicleId,
                                   Sim = w.simId,
                                   WarningType = w.warntype
                               };

            List<string> paramaters = new List<string>();
            for (int i = 0; i < vehicleSim.Count; i++)
            {
                paramaters.Add(vehicleSim[i].ToVarcharSqlParam());
            }
            paramaters.Add(startTime.ToVarcharSqlParam());
            paramaters.Add(endTime.ToVarcharSqlParam());
            string warningsJsonStr = RealTimeGet.getReportFromGeoBase(CommonFunctions.GetLoginUser().UserId, CommonFunctions.GetSQL(warnings, paramaters), startTime, endTime, "0");
            List<WarningInfo> warningList = CommonFunctions.JsonStrToObject<List<WarningInfo>>(warningsJsonStr);

            //给警报类型填充上级单位id信息
            var warningUnitId=from w in warningList
                              from v in vehicleList
                              where w.Sim==v.Sim
                              select new WarningInfo()
                              {
                                  VehicleId = w.VehicleId,
                                  Sim = w.Sim,
                                  WarningType = w.WarningType,
                                  ParentUnitId=v.ParentUnitId
                              };
            warningList = warningUnitId.ToList();

            //开始统计
            foreach(UnitWarningStatistics item in unitWarnings)
            {
                item.WarningsCount=(from w in warningList where w.ParentUnitId==item.UnitId select w.ParentUnitId).Count();
                item.WarningTypesCount=(from w in warningList where w.ParentUnitId==item.UnitId select w.WarningType).Distinct().Count();
            }

            Session["SearchData"] = unitWarnings;
            return PartialView(unitWarnings.ToPagedList(pageIndex,CommonDictionary.PageSize));
        }

        public ActionResult ExportData()
        {
            CommonController controller = new CommonController();
            Dictionary<string, string> title = new Dictionary<string, string>();
            title.Add("UnitName", "单位名称");
            title.Add("ParentUnitName", "上级单位名称");
            title.Add("WarningTypesCount", "警报类型数");
            title.Add("WarningsCount", "警报总数");
            string fileName = "单位警报统计";
            if (Session["SearchData"] != null)
            {
                return controller.ListToExcel<UnitWarningStatistics>((Session["SearchData"] as IEnumerable<UnitWarningStatistics>).ToList(), title, fileName,Server);
            }
            else
            {
                ViewBag.Message = "数据已过期，请重新查询";
                return View("ActionResult");
            }
        }
    }
}
